package com.code.question5.impl;

import com.alibaba.fastjson.JSON;
import com.code.question5.base.MessageType;
import com.code.question5.base.ResponseType;
import com.code.question5.model.ResponseMessage;
import com.code.question5.model.SendMessage;
import com.code.question5.model.User;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

/**
 * 客户端服务类
 */
public class CustomerServiceImpl {
    private Map<String, ReciveMessageServiceImpl> onlineReciveService = new HashMap<>();
    private Map<String, Thread> onlineReciveThread = new HashMap<>();

    /**
     * 构造序列化用户数据，读入缓存
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public CustomerServiceImpl() throws IOException, ClassNotFoundException {
        File file = new File("");
        String projectPath = file.getCanonicalPath();
        String diskPath = projectPath.substring(0, projectPath.indexOf("\\") + 1);
        File userFile = new File(diskPath + "Repository\\user.txt");
        if (userFile.exists()) {
            //反序列化对象信息
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(userFile));
            List<User> users = (List<User>) ois.readObject();
            UserServiceImpl userService = new UserServiceImpl();
            for (User stu : users) {
                userService.PostUser(stu);
            }
            ois.close();
        }
    }

    /**
     * 首页
     *
     * @return
     * @throws IOException
     */
    public User Index() throws IOException {
        System.out.println("------------------------------------------------------");
        System.out.println("--------------------欢迎来到拉勾Talk-------------------");
        System.out.println("----------1.登录 \t \t2.注册\t \t 0.退出-----------");
        System.out.println("------------------请输入对应的菜单编号-----------------");
        String menu = new BufferedReader(new InputStreamReader(System.in)).readLine();
        switch (menu) {
            case "1":
                return Login();
            case "2":
                return Register();
            default:
                System.out.println("退出？这辈子是不可能退出的，来独撸到天明！！！");
                return null;
        }
    }

    /**
     * 登录页
     *
     * @return
     * @throws IOException
     */
    public User Login() throws IOException {
        System.out.println("请输入账号：");
        String name = new BufferedReader(new InputStreamReader(System.in)).readLine();
        System.out.println("请输入密码：");
        String password = new BufferedReader(new InputStreamReader(System.in)).readLine();
        UserServiceImpl usi = new UserServiceImpl();
        User user = new User(name, password);
        String result = usi.Login(user);
        ResponseMessage rm = JSON.parseObject(result, ResponseMessage.class);
        if (rm.getCode().equals(ResponseType.SUCCESS)) {
            user.setLogin(true);
            return user;
        } else {
            System.out.println("登录失败，账户名或密码错误！");
            return null;
        }
    }

    /**
     * 注册页
     *
     * @return
     * @throws IOException
     */
    public User Register() throws IOException {
        System.out.println("请输入账号：");
        String name = new BufferedReader(new InputStreamReader(System.in)).readLine();
        System.out.println("请输入密码：");
        String password = new BufferedReader(new InputStreamReader(System.in)).readLine();
        UserServiceImpl usi = new UserServiceImpl();
        User user = new User(name, password);
        String result = usi.Register(user);
        ResponseMessage rm = JSON.parseObject(result, ResponseMessage.class);
        if (rm.getCode().equals(ResponseType.SUCCESS)) {
            user.setLogin(true);
            return user;
        } else {
            System.out.println("该用户已存在，请更换用户名重新注册！");
            return null;
        }
    }

    /**
     * 菜单页
     */
    public void Menu() {
        System.out.println("------------------------------------------------------");
        System.out.println("--------------------欢迎来到拉勾Talk-------------------");
        System.out.println("----------1.群聊 \t \t2.上传文件\t \t 0.退出-----------");
        System.out.println("------------------请输入对应的菜单编号-----------------");
    }

    /**
     * 群聊
     *
     * @param s
     * @param user
     * @throws IOException
     */
    public void Talk(Socket s, User user) throws IOException, InterruptedException {
        System.out.println("欢迎进入拉勾奇葩说聊天室！(输入:q回主菜单)");
        Vector<InputStream> streams = new Vector<>();
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        SequenceInputStream sis = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!onlineReciveThread.containsKey(user.getName())) {
            ReciveMessageServiceImpl reciveMessageService = new ReciveMessageServiceImpl(br);
            Thread reciveThread = new Thread(reciveMessageService);
            reciveThread.start();
            onlineReciveThread.put(user.getName(), reciveThread);
            onlineReciveService.put(user.getName(), reciveMessageService);
        }
        while (true) {
            streams.clear();
            String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
            if (str.equalsIgnoreCase(":q")) {
                break;
            }
            SendMessage sendMessage = new SendMessage();
            sendMessage.setMessageType(MessageType.TEXT);
            sendMessage.setContent(str);
            sendMessage.setTime(System.currentTimeMillis());
            String jsonStr = JSON.toJSONString(sendMessage);
            byte[] contentByte = jsonStr.getBytes();
            streams.addElement(new ByteArrayInputStream(contentByte));
            sis = new SequenceInputStream(streams.elements());
            int len = 0;
            byte[] cacheBuf = new byte[1024];
            while ((len = sis.read(cacheBuf)) != -1) {
                bos.write(cacheBuf, 0, len);
            }
            bos.flush();
            System.out.println(sdf.format(sendMessage.getTime()) + "----" + user.getName() + ":" + str);
        }
        if (null != sis) {
            sis.close();
        }
    }

    /**
     * 文件上传
     *
     * @param s
     * @param user
     * @throws IOException
     */
    public void Upload(Socket s, User user) throws IOException {
        Vector<InputStream> streams = new Vector<>();
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        SequenceInputStream sis = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JFileChooser jfc = new JFileChooser();
        if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = jfc.getSelectedFile();
            if (file.isFile()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                SendMessage sendMessage = new SendMessage();
                sendMessage.setMessageType(MessageType.FILE);
                sendMessage.setName(file.getName());
                sendMessage.setLength(file.length());
                sendMessage.setTime(System.currentTimeMillis());
                String jsonStr = JSON.toJSONString(sendMessage);
                byte[] jsonByte = jsonStr.getBytes();
                byte[] contentByte = new byte[1024];
                for (int i = 0; i < jsonByte.length; i++) {
                    contentByte[i] = jsonByte[i];
                }
                streams.addElement(new ByteArrayInputStream(contentByte));
                streams.addElement(fileInputStream);
                sis = new SequenceInputStream(streams.elements());
                int len = 0;
                byte[] cacheBuf = new byte[1024];
                System.out.println("正在玩命的上传。。。");
                long uploadLen = 0;
                while ((len = sis.read(cacheBuf)) != -1) {
                    bos.write(cacheBuf, 0, len);
                    uploadLen += len;
                    System.out.println("已上传" + uploadLen + "字节");
                }
                bos.flush();
                System.out.println("上传成功。。。");
            } else {
                System.out.println("请选择具体的文件上传");
            }
        } else {
            System.out.println("请选择具体的文件上传");
        }
    }

    /**
     * 登出
     *
     * @param user
     */
    public void Logout(User user) {
        Thread reciveMessageThread = onlineReciveThread.get(user.getName());
        ReciveMessageServiceImpl reciveMessageService = onlineReciveService.get(user.getName());
        if (null != reciveMessageThread) {
            reciveMessageService.exit = false;
            reciveMessageThread.interrupt();
        }
    }
}
